package examples;

import java.util.concurrent.Semaphore;

/**
 * @author Jay
 */
public class SemaphoreExample {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2);
        Thread t1 = new Thread(() -> {
            try {
                System.out.println("t1 尝试获取信号量");
                semaphore.acquire();
                System.out.println("t1 获得信号量");
                Thread.sleep(2000);
                System.out.println("t1 释放信号量");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                System.out.println("t2 尝试获取信号量");
                semaphore.acquire();
                System.out.println("t2 获得信号量");
                Thread.sleep(2000);
                System.out.println("t2 释放信号量");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t3 = new Thread(() -> {
            try {
                System.out.println("t3 尝试获取信号量");
                semaphore.acquire();
                System.out.println("t3 获得信号量");
                Thread.sleep(2000);
                System.out.println("t3 释放信号量");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
